﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public class CameraController : MonoBehaviour 
{
	private Camera m_camera;

	private ICameraDefinition m_defaultCameraDefinition;
	
	public List<ICameraDefinition> CameraDefinitions;

	public float CameraLookAtLerpSpeed = .05f;
	public float CameraPositionLerpSpeed = .05f;
	
	public Transform LinkTransform;

	public CameraController()
	{
		CameraDefinitions =  new List<ICameraDefinition>();

		// Initialize ThirdPersonCameraDefinition
		m_defaultCameraDefinition = new ThirdPersonCameraDefinition(this);

		CameraDefinitions.Add(m_defaultCameraDefinition);
	}
	
	// Use this for initialization
	void Start()
	{
	}

	// Use this for initialization
	void Awake()
	{
		// Get the camera.
		m_camera = GetComponent<Camera>();
	}
	
	Vector3 GetCameraLookAt(ICameraDefinition cameraDefinition)
	{
		// This makes the transition smooth.
		return Vector3.Lerp(m_camera.transform.position, cameraDefinition.GetCameraLookAt(), CameraLookAtLerpSpeed);
	}

	Vector3 GetCameraPosition(ICameraDefinition cameraDefinition)
	{
		// This makes the transition smooth.
		return Vector3.Lerp(m_camera.transform.position, cameraDefinition.GetCameraPosition(), CameraPositionLerpSpeed);
	}
	
	// Update is called once per frame
	void LateUpdate()
	{
		// Select the first camera that states that it's active.
		ICameraDefinition currentCamera = CameraDefinitions.FirstOrDefault(x => x.CameraActive());

		// Defaults camera
		if (currentCamera == null)
		{
			currentCamera = m_defaultCameraDefinition;
		}

		// Sets the camera position.
		m_camera.transform.position = GetCameraPosition(currentCamera);

		// This needs to be the last line.
		// This sets camera location.
		m_camera.transform.LookAt(GetCameraLookAt(currentCamera));
	}
}
